package com.labofjet.messagesender.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.labofjet.common.util.IdUtils;
import com.labofjet.common.util.JSONUtils;
import com.labofjet.message.dto.MsgMessageSenderDto;
import com.labofjet.message.dto.MsgShortMessageTemplateDto;
import com.labofjet.message.dto.MsgShortMessageTemplateExample;
import com.labofjet.message.service.impl.MsgShortMessageTemplateServiceImpl;
import com.labofjet.messagesender.utils.SmsUtils;
import com.labofjet.system.dto.SysUserDto;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 手机短信发送服务
 */
@Service
public class SdrShortMessageSenderServiceImpl extends SdrBaseMessageSenderServiceImpl {

    @Autowired
    private SmsUtils smsUtils;

    @Autowired
    private MsgShortMessageTemplateServiceImpl msgShortMessageTemplateService;


    @Override
    protected MsgMessageSenderDto handlerInternal(MsgMessageSenderDto msgMessageSenderDto, SysUserDto sysUserDto) {
        if (StringUtils.isEmpty(sysUserDto.getPhoneNumber())) {
            log.error("用户手机号为空 {}", sysUserDto);
            throw new IllegalStateException("用户手机为空 " + sysUserDto.getUsername());
        }
        Integer templateId = msgMessageSenderDto.getTemplateId();
        MsgShortMessageTemplateExample msgShortMessageTemplateExample = new MsgShortMessageTemplateExample();
        msgShortMessageTemplateExample.createCriteria().andIdEqualTo(templateId);
        List<MsgShortMessageTemplateDto> msgShortMessageTemplateDtos = msgShortMessageTemplateService.selectByExample(msgShortMessageTemplateExample);
        if (CollectionUtils.isEmpty(msgShortMessageTemplateDtos)) {
            log.error("未找到模板数据 {}, {}", msgMessageSenderDto, sysUserDto);
            throw new RuntimeException("未找到模板数据, id= " + templateId);
        }
        MsgShortMessageTemplateDto msgShortMessageTemplateDto = msgShortMessageTemplateDtos.get(0);
        Map<String, String> realTemplateParamsMap = msgMessageSenderDto.getRealTemplateParamsMap();
        if (MapUtils.isNotEmpty(realTemplateParamsMap)) {
            Map<String, Object> map = JSONUtils.stringToDto(msgShortMessageTemplateDto.getTemplateParam(), Map.class);
            if (map.containsKey("to")) {
                realTemplateParamsMap.put("to", sysUserDto.getUsername());
            }
            if (map.containsKey("username")) {
                realTemplateParamsMap.put("username", sysUserDto.getUsername());
            }
            if (map.containsKey("random")) {
                realTemplateParamsMap.put("random", IdUtils.uuid().substring(0, 20));
            }
            if (map.containsKey("time")) {
                realTemplateParamsMap.put("time", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            }
            msgShortMessageTemplateDto.setRealTemplateParam(JSONUtils.dtoToString(realTemplateParamsMap));
        }
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = smsUtils.sendSms(msgShortMessageTemplateDto, sysUserDto); // 调用发送接口
        } catch (ClientException e) {
            log.error("发送短信失败, message= {}", e.getErrMsg());
            throw new RuntimeException(e);
        }
        if (!"OK".equals(sendSmsResponse.getCode())) {
            log.error("发送短信失败 message:{} bizId:{}, code:{}, obj:{}", sendSmsResponse.getMessage(), sendSmsResponse.getBizId(), sendSmsResponse.getCode(), sendSmsResponse);
            throw new RuntimeException(MessageFormat.format("发送短信失败 message:{0} bizId:{1}, code:{2}, obj:{3}", sendSmsResponse.getMessage(), sendSmsResponse.getBizId(), sendSmsResponse.getCode(), sendSmsResponse));
        }


        // TODO 成功失败都应该保存数据
        return msgMessageSenderDto;
    }


}

